package com.wxl.xueyuan.fragment;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Message;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.wxl.xueyuan.MyApp;
import com.wxl.xueyuan.R;
import com.wxl.xueyuan.activity.DetailActivity;
import com.wxl.xueyuan.adapter.ArticleAdapter;
import com.wxl.xueyuan.api.Api;
import com.wxl.xueyuan.api.ApiConfig;
import com.wxl.xueyuan.api.MCallback;
import com.wxl.xueyuan.entity.ArticleEntity;
import com.wxl.xueyuan.entity.ArticleListResponse;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import lombok.SneakyThrows;

public class ArticleFragment extends BaseFragment {

    private int categoryId;
    private RecyclerView recyclerView;
    private RefreshLayout refreshLayout;
    private int pageNum = 1;
    private ArticleAdapter articleAdapter;
    private List<ArticleEntity> datas = new ArrayList<>();
    private LinearLayoutManager linearLayoutManager;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    articleAdapter.setDatas(datas);
                    articleAdapter.notifyDataSetChanged();
                    break;
            }
        }
    };

    public ArticleFragment() {
    }

    public static ArticleFragment newInstance(int categoryId) {
        ArticleFragment fragment = new ArticleFragment();
        fragment.categoryId = categoryId;
        return fragment;
    }


    @Override
    protected int initLayout() {
        return R.layout.fragment_article;
    }

    @Override
    protected void initView() {
        recyclerView = mRootView.findViewById(R.id.recyclerView);
        refreshLayout = mRootView.findViewById(R.id.refreshLayout);
    }

    @Override
    protected void initData() {
        linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        articleAdapter = new ArticleAdapter(getActivity());
        recyclerView.setAdapter(articleAdapter);
        articleAdapter.setOnItemClickListener(new ArticleAdapter.OnItemClickListener() {
            @SneakyThrows
            @Override
            public void onItemClick(Serializable obj) {
                ArticleEntity articleEntity = (ArticleEntity) obj;
                //更改图片url
                String str = "<img.*src=.*width.*>";
                List<String> photos = articleEntity.getPhotos();
                String rawHtml = articleEntity.getRawHtml();
                for (int i = 0; i < photos.size(); i++) {
                    StringBuffer sb = new StringBuffer();
                    sb.append("<img src=\"").append(photos.get(i)).append("\"><br /><br />");
                    rawHtml = rawHtml.replaceFirst(str, sb.toString());
                }
                articleEntity.setRawHtml(rawHtml);
                //发送文章和浏览记录
                new Thread(new Runnable() {
                    @SneakyThrows
                    @Override
                    public void run() {
                        HashMap<String, Object> params = new HashMap<>();
                        params.put("recordId", articleEntity.getRecordId());
                        params.put("title", articleEntity.getTitle());
                        params.put("publishedAt", articleEntity.getPublishedAt());
                        params.put("ID", MyApp.getmData("ID"));
                        Api.config("/article/addVisitArticle", params).getRequest(getActivity(), new MCallback() {
                            @Override
                            public void onSuccess(final String res) {
                                System.out.println(res);
                                String thumb_up_state = "0";
                                String collection_state = "0";
                                switch (res) {
                                    case "01" :
                                        collection_state = "1";
                                        break;
                                    case "10" :
                                        thumb_up_state = "1";
                                        break;
                                    case "11" :
                                        collection_state = "1";
                                        thumb_up_state = "1";
                                        break;
                                }
                                //跳转详情页面
                                Bundle bundle=new Bundle();
                                bundle.putString("record_id", String.valueOf(articleEntity.getRecordId()));
                                bundle.putString("title", articleEntity.getTitle());
                                bundle.putString("published_at", articleEntity.getPublishedAt());
                                bundle.putString("raw_html", articleEntity.getRawHtml());
                                bundle.putString("thumb_up_state", thumb_up_state);
                                bundle.putString("collection_state", collection_state);
                                navigateToWithBundle(DetailActivity.class, bundle);
                            }
                            @Override
                            public void onFailure(Exception e) {

                            }
                        });
                    }
                }).start();
            }
        });
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageNum = 1;
                getArticleList(true);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                pageNum++;
                getArticleList(false);
            }
        });
        getArticleList(true);
    }

    private void getArticleList(final boolean isRefresh) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("page", pageNum);
        params.put("size", ApiConfig.PAGE_SIZE);
        String url = "";
        switch (categoryId) {
            case 0 :
                url = "/cs/news";
                break;
            case 1 :
                url = "/cs/notices";
                break;
            case 2 :
                url = "/sw/news";
                break;
            case 3 :
                url = "/sw/notices";
                break;
            case 4 :
                url = "/jwc/news";
                break;
            case 5 :
                url = "/jwc/notices";
                break;
        }
        Api.otherConfig(url, params).getRequest(getActivity(), new MCallback() {
            @SneakyThrows
            @Override
            public void onSuccess(final String res) {
                if (isRefresh) {
                    refreshLayout.finishRefresh(true);
                } else {
                    refreshLayout.finishLoadMore(true);
                }
                ObjectMapper mapper = new ObjectMapper();
                ArticleListResponse response = mapper.readValue(res, ArticleListResponse.class);
                if (response != null) {
                    List<ArticleEntity> list = response.getItems();
                    if (list != null && list.size() > 0) {
                        if (isRefresh) {
                            datas = list;
                        } else {
                            datas.addAll(list);
                        }
                        mHandler.sendEmptyMessage(0);
                    } else {
                        if (isRefresh) {
                            showToastSync("暂时无数据");
                        } else {
                            showToastSync("没有更多数据");
                        }
                    }
                }
            }

            @Override
            public void onFailure(Exception e) {
                if (isRefresh) {
                    refreshLayout.finishRefresh(true);
                } else {
                    refreshLayout.finishLoadMore(true);
                }
            }
        });
    }
}